package com.lanhe.common.utils.haoka;


import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.lanhe.common.utils.StringUtils;
import com.lanhe.common.utils.haoka.dto.OrdersHaokaApplyDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 号卡
 *
 * @author zhanggl
 * @date 2023年12月25日22:51:31
 */
@Component
@Slf4j
public class HaokaUtil {

	@Value("${lanhe.haoka.aesKey}")
	private String aesKey;

	@Value("${lanhe.haoka.apiToken}")
	private String apiToken;

	@Value("${lanhe.haoka.shareId}")
	private String shareId;

	@Value("${lanhe.haoka.applyURL}")
	private String applyURL;


	/**
	 * 敢探号提单V2
	 *
	 * @return java.lang.String
	 * @author zhanggl
	 * @date 2023/12/4
	 */
	public String purchaseApply(OrdersHaokaApplyDto haokaApplyDto) throws Exception {

		Map<String, String> formParams = new LinkedHashMap<>();
		formParams.put("share_id", shareId);
		formParams.put("sku", haokaApplyDto.getSku());
		formParams.put("source_id", haokaApplyDto.getSourceId());

		// 获取秘钥
		String sign = StringUtils.generateSignatureHaoka(formParams, apiToken);
		formParams.put("id_name", StringUtils.encryptAes(haokaApplyDto.getIdName(), aesKey));
		formParams.put("id_num", StringUtils.encryptAes(haokaApplyDto.getIdNum(), aesKey));
		formParams.put("mobile", StringUtils.encryptAes(haokaApplyDto.getMobile(), aesKey));
		formParams.put("name", StringUtils.encryptAes(haokaApplyDto.getName(), aesKey));
		formParams.put("province_code", haokaApplyDto.getProvinceCode().toString());
		formParams.put("province", haokaApplyDto.getProvince());
		formParams.put("city_code", haokaApplyDto.getCityCode().toString());
		formParams.put("city", haokaApplyDto.getCity());
		formParams.put("district_code", haokaApplyDto.getDistrictCode().toString());
		formParams.put("district", haokaApplyDto.getDistrict());
		formParams.put("address", StringUtils.encryptAes(haokaApplyDto.getAddress(), aesKey));
		formParams.put("pretty_number", haokaApplyDto.getPrettyNumber());
		formParams.put("sign", sign);
		long startTime = System.currentTimeMillis();
		String result = HttpRequest.post(applyURL).body(JSON.toJSONString(formParams)).execute().body();
		log.info("[{}] [purchaseApply] ======>请求 {}", this.getClass().getSimpleName(),
				applyURL);
		log.info("[{}] [purchaseApply] ======>返回 {}", this.getClass().getSimpleName(),
				result);
		log.info("[{}] [purchaseApply] ======>耗时 {}", this.getClass().getSimpleName(),
				(System.currentTimeMillis() - startTime));
		return result;
	}


	public String getApiToken() {
		return apiToken;
	}

	public void setApiToken(String apiToken) {
		this.apiToken = apiToken;
	}
}
